package com.canis.stockmanager.web;

import com.canis.stockmanager.comm.aop.LoggerManage;
import com.canis.stockmanager.domai.Resource;
import com.canis.stockmanager.domai.Server;
import com.canis.stockmanager.domai.Stock;
import com.canis.stockmanager.domai.result.Combox;
import com.canis.stockmanager.domai.result.ExceptionMsg;
import com.canis.stockmanager.domai.result.ResponseData;
import com.canis.stockmanager.repository.BoxVersionRepository;
import com.canis.stockmanager.repository.OperatorRepository;
import com.canis.stockmanager.repository.ServerRepository;
import com.canis.stockmanager.repository.StockRepository;
import com.canis.stockmanager.utils.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.*;


@Controller
@RequestMapping("/stock")
public class StockController extends BaseController {
    @Autowired
    private StockRepository stockRepository;
    @Autowired
    private ServerRepository serverRepository;
    @Autowired
    private BoxVersionRepository boxVersionRepository;
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    @ResponseBody
    public ResponseData query(Model model, @RequestParam(value = "start", defaultValue = "0") Integer start, @RequestParam(value = "sort", defaultValue = "") String sortStr,
                              @RequestParam(value = "limit", defaultValue = "10") Integer limit, Stock stock, HttpServletResponse response) {
        Pageable pageable = util.getPageable(sortStr,start,limit);
        Page<Stock> pages=null;
        if(stock.getStockState()==null){
            pages=stockRepository.findByBoxMacContainingAndBoxNumberContaining(stock.getBoxMac(),stock.getBoxNumber(),pageable);
        }else{
            pages= stockRepository.findByStockStateAndBoxMacContainingAndBoxNumberContaining(stock.getStockState(),stock.getBoxMac(),stock.getBoxNumber(),pageable);
        }
        List<Stock> lists=pages.getContent();
        return new ResponseData(ExceptionMsg.SUCCESS, "",pages.getTotalElements(),lists);
    }
    @RequestMapping(value = "/addOrEdit", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData addOrEdit(@RequestParam(value = "boxNumber", defaultValue = "") String boxNumber,
                                  @RequestParam(value = "boxMac", defaultValue = "") String boxMac,
                                  @RequestParam(value = "box_version", defaultValue = "") String box_version,
                                  @RequestParam(value = "mem", defaultValue = "") String mem,

                                  @RequestParam(value = "id", defaultValue = "0") int id,  HttpServletResponse response) {
        Stock stock;
        ExceptionMsg em=ExceptionMsg.SUCCESS;
        if(id>0){
            stock=stockRepository.findById(id);
        }else{
            stock=new Stock();
            if(boxMac==null||boxMac.equals("")){
                em=ExceptionMsg.BoxMacIsNull;
            }else if(stockRepository.findByBoxMac(boxMac)!=null){
                em=ExceptionMsg.BoxmacAlreadyExists;
            }else{
                boxMac=boxMac.replaceAll(":", "").replaceAll("-", "").toLowerCase();
                stock.setUuid(UUID.randomUUID().toString().replace("-", "").toLowerCase());
                stock.setStockState(0);
                stock.setBoxMac(boxMac);
                stock.setStock_ru_time(new Date());
                stock.setBox_version(box_version==null?"":box_version);
                stock.setBoxNumber(boxNumber);
                stock.setEnd_time(addYDate());
            }
        }
        //stock.setBox_type(box_type+"");
        stock.setMem(mem);
        if(em.getCode().equals("000000")){
            try{
                stockRepository.save(stock);
            }catch (Exception e){
                e.printStackTrace();
                if(id>0){
                    em=ExceptionMsg.EditError;
                }else{
                    em=ExceptionMsg.AddError;
                }

            }

        }

        return new ResponseData(em);
    }
    @RequestMapping(value = "/queryServerCB", method = RequestMethod.GET)
    @ResponseBody
    public ResponseData queryServerCB(Model model, @RequestParam(value = "query", defaultValue = "") String query, HttpServletResponse response) {
        Pageable pageable = util.getPageable("id",0,50);
        Page<Server> pages=serverRepository.findByIpContainingOrPortContaining(query,query,pageable);
        List<Server> lists=pages.getContent();
        List<Combox> cbs=new ArrayList<Combox>();
        Combox cb;
        for (Server s:lists) {
            cb=new Combox(s.getIp()+"-"+s.port,s.getId()+"");
            cbs.add(cb);
        }
        return new ResponseData(ExceptionMsg.SUCCESS, "",pages.getTotalElements(),cbs);
    }


    @RequestMapping(value = "/queryBoxVersionCB", method = RequestMethod.GET)
    @ResponseBody
    public ResponseData queryBoxVersionCB(Model model, HttpServletResponse response) {

        List<Combox> cbs=boxVersionRepository.find();
        return new ResponseData(ExceptionMsg.SUCCESS, "",0,cbs);
    }
    @RequestMapping(value="/",method= RequestMethod.GET)
    public String stock(Model model) {

        return "stock";
    }
    private static Date addYDate(){
        Calendar cd=Calendar.getInstance();//获取一个Calendar对象
        try{
            cd.setTime(new Date());//设置calendar日期
        }catch(Exception e){
            e.printStackTrace();
        }
        cd.add(Calendar.YEAR,1);
        return cd.getTime();
    }
}
